﻿/*HCRain    追雨潮开发框架   hcrain.cn   by:hechao*/
/*有大量引用   H-ui.js v2.3  特此说明  by hechao */
//全局变量
var spPageUrl = "../ashx/spui.ashx";//后台统一页面
var spPageHtmlName = "本html名称";//如index
var pTableName = "";//增删改的，表名
var pTableIdName = "";//增删改的，表主键
var grid1ID = "";//列表的ID
var selTableinfo = "";//查询table信息 主表一定要as T 
var selFieldsinfo = "*";//查询返回的内容
var pPageCode = "";
var pPageInfoName = "-";
//$(document).ajaxComplete(function (event, xhr, settings) {
//    console.log(1111111111111222222222111);
//    console.log(event);
//    console.log(xhr);
//});
//$(document).ajaxSuccess(function (event, xhr, settings) {
//    console.log(1111111111111111);
//    console.log(event);
//    console.log(xhr);
//});

//权限获取
var ptoolbar = [];
//设置页面基本信息
function spsetBase(tname, tid, sinfo, sre, mgid, pcode, infoname, HtmlName) {

    pTableName = tname;
    pTableIdName = tid;
    selTableinfo = sinfo;
    selFieldsinfo = sre;
    grid1ID = mgid;
    pPageCode = pcode;
    pPageInfoName = infoname;

    spPageHtmlName = HtmlName;
    HCUser = createObject("sys");
    ptoolbar = getToolBar();

    if (typeof (vum) != "undefined" && vum != null && vum != "undefined") {
        vum.toolbars = ptoolbar;
    }
}
function spsetBaseNoBt(tname, tid, sinfo, sre, mgid, pcode, infoname, HtmlName) {

    pTableName = tname;
    pTableIdName = tid;
    selTableinfo = sinfo;
    selFieldsinfo = sre;
    grid1ID = mgid;
    pPageCode = pcode;
    pPageInfoName = infoname;
    spPageHtmlName = HtmlName;
    HCUser = createObject("sys");
}
//////////全局用户信息
var HCUser = null;//createObject("sys");
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}
function replaceAll2(content, oldReplace, newReplace) {
    var i;
    for (i = 0; i < content.length; i++) {
        if (content.indexOf(oldReplace) > 0) {
            content = content.replace(oldReplace, newReplace);
        }
    }
    return content;
}
//////////////////**********************主表的删查

//获取查询url 表查
//function spselUrl(spadd) spadd:添加的查询条件  subinfo字查询信息
function spselUrl(spadd, subinfo) {
    var infoadd = "";
    if (spadd != null && spadd != "undefined" && spadd.length > 0) {
        infoadd += "&wheresp= " + escape(spadd);
        // return spPageUrl + "?action=sel&tableinfo=" + escape(selTableinfo) + "&refields=" + escape(selFieldsinfo) + "&wheresp= " + escape(spadd);
    }
    if (subinfo != null && subinfo != "undefined" && subinfo.length > 0) {
        infoadd += "&subinfo= " + escape(subinfo);

    }
    return spPageUrl + "?action=sel&tableinfo=" + escape(selTableinfo) + "&refields=" + escape(selFieldsinfo) + infoadd;
}
//获取查询行url 
//function spselrowUrl(id)
function spselrowUrl(id) {
    return spPageUrl + "?action=GetTableObjINFO&talbename=" + escape(pTableName) + "&midname=" + escape(pTableIdName) + "&midvalue=" + id;
}
//获取DEL url
//function spdelUrl(id)
function spdelUrl(id) {
    return spPageUrl + "?action=del&tablename=" + escape(pTableName) + "&tablemidname=" + escape(pTableIdName) + "&id=" + id + "&timenow=" + new Date().getTime();
}


//查询树结构
//function sposelTreeUrl(t, r, wa)
function sposelTreeUrl(t, r, wa) {
    if (wa != null && wa != "undefined" && wa.length > 0)
    { return spPageUrl + "?action=seltree&tableinfo= " + t + "&refields= " + r + "&wheresp= " + wa; }
    else
        return spPageUrl + "?action=seltree&tableinfo= " + t + "&refields= " + r + "";
}


function sposelUrl(t, r, wa) {
    if (wa != null && wa != "undefined" && wa.length > 0)
    { return spPageUrl + "?action=sel&tableinfo=" + t + "&refields=" + r + "&wheresp= " + wa; }
    else
        return spPageUrl + "?action=sel&tableinfo=" + t + "&refields=" + r + "";
}
function spodelUrl(t, k, id) {
    return spPageUrl + "?action=del&tablename=" + t + "&tablemidname=" + k + "&id=" + id + "&timenow=" + new Date().getTime();
}

//获取查询url_sql(包含 状态+行数据)
function sposelUrlBySql(sqlinfo) {
    return spPageUrl + "?action=SqlTableGet&sqlinfo=" + escape(sqlinfo);
}
//获取查询url_sql（只有行数据）
//function sposelUrlBySqlNoState(sqlinfo)
function sposelUrlBySqlNoState(sqlinfo) {
    return spPageUrl + "?action=SqlTableGet&nostate=no&sqlinfo=" + escape(sqlinfo);
}

//获取查询url_sql(包含 状态+行数据)
function sposelUrlByF(s, t, w, g, h, o) {

    var re = spPageUrl + "?action=SqlTableGet&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    re = re.replaceAll("'", "hcdhc");
    return re;
}
//获取查询url_sql（只有行数据）
function sposelUrlByFNoState(s, t, w, g, h, o) {

    var re = spPageUrl + "?action=SqlTableGet&nostate=no&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    re = re.replaceAll("'", "hcdhc");
    return re;
}

//同步请求后台，要求后台，返回直接的json串
function spGetJson(url) {
    var re;
    $.ajax({
        type: "post",
        url: url,
        //  data: "test=" + test,
        async: false,
        success: function (data) {
            re = data;
        }
    });
    return re;
}
var toolbartext = "";
function getToolBar() {
    var toolbar = [];
    $.ajax({
        url: "../ashx/sp.ashx?action=getbuttonaccess&pagecode=" + pPageCode + "&userid=" + HCUser.HCUide,
        type: "post",
        dataType: "json",
        timeout: 5000,
        async: hcui_ajaxasync,
        cache: false,
        success: function (data) {

            if (data.toolbar != undefined && data.toolbar != '') {
                $.each(data.toolbar, function (index, row) {
                    //var handler = row.handler;
                    //row.handler = function () { eval(handler); };
                    toolbar.push(row);
                    //toolbartext += row.text + "-";
                });
            }
        }
    });
    return toolbar;
}
function setToolBar(btstring) {
    var data = $.parseJSON(btstring);
    var toolbar = [];
    if (data.toolbar != undefined && data.toolbar != '') {

        $.each(data.toolbar, function (index, row) {
            var handler = row.handler;
            row.handler = function () { eval(handler); };
            toolbar.push(row);
        });
    }
    ptoolbar = toolbar;
}
var base_ashx_url = "../ashx/sp.ashx";
function createObject(dowhat) {

    var obj = new Object();
    //从cookie取，如果没有--或者禁用了（从后台取中取）
    if (dowhat == "reload" || hcgetCookie("HCUid") == "" || pPageCode == "index") {
        var linfo = spGetJson(base_ashx_url+"?action=getLogininfo&timenow=" + new Date().getTime());
        if (linfo.indexOf("会话超时") > 0) {
            parent.location.href = "/";
            //window.location.href = "../login.html";
            return;
        }
        var lobj = $.parseJSON(linfo);

        obj.HCUide = lobj[0].HCUid;
        obj.HCUname = lobj[0].HCUname;
        obj.HCUtitle = lobj[0].HCUtitle;
        obj.HCUorg = lobj[0].HCUorg;
        obj.HCUdep = lobj[0].HCUdep;
        obj.HCUorgtype = lobj[0].HCUorgtype;
        obj.HCUorgName = lobj[0].HCUorgName;
        obj.HCUdepName = lobj[0].HCUdepName;
        obj.HCUorgCode = lobj[0].HCUorgCode;

        hcsetCookie("HCUid", obj.HCUide, 1);
        hcsetCookie("HCUname", obj.HCUname, 1);
        hcsetCookie("HCUtitle", obj.HCUtitle, 1);
        hcsetCookie("HCUorg", obj.HCUorg, 1);
        hcsetCookie("HCUdep", obj.HCUdep, 1);
        hcsetCookie("HCUorgtype", obj.HCUorgtype, 1);
        hcsetCookie("HCUorgName", obj.HCUorgName, 1);
        hcsetCookie("HCUdepName", obj.HCUdepName, 1);
        hcsetCookie("HCUorgCode", obj.HCUorgCode, 1);
    }
    else {
        obj.HCUide = hcgetCookie("HCUid");
        obj.HCUname = hcgetCookie("HCUname");
        obj.HCUtitle = hcgetCookie("HCUtitle");
        obj.HCUorg = hcgetCookie("HCUorg");
        obj.HCUdep = hcgetCookie("HCUdep");
        obj.HCUorgtype = hcgetCookie("HCUorgtype");
        obj.HCUorgName = hcgetCookie("HCUorgName");
        obj.HCUdepName = hcgetCookie("HCUdepName");
        obj.HCUorgCode = hcgetCookie("HCUorgCode");
    }

    return obj;
}
//cookie
function hcsetCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";;
}
//获取cookie
function hcgetCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}
//清除cookie  
function hcclearCookie(name) {
    setCookie(name, "", -1);
}

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}

//本页面查找
function hctsel(whereadd, callback) {
    $.get(spselUrl(whereadd),
            function (data) {
                callback(data);
            });
}
//删除指定数据
function hcdodel(tablename, tablekey, tablekeyid, callback) {
    $.get(spodelUrl(tablename, tablekey, tablekeyid),
                  function (data) {
                      var data = JSON.parse(data);
                      switch (data.message) {
                          case JsonResult.SessionOut:
                              $.messager.alert('系统出错', ' 登录超时，请重新登录!');
                              callback("timeout");
                              break;
                          case JsonResult.Error:
                              $.messager.alert('系统出错', data.data);
                              callback("error");
                              break;
                          case JsonResult.Success:
                              $.messager.show({
                                  title: '提示信息',
                                  msg: data.data,
                                  showType: 'show'
                              });
                              callback("ok");
                              break;
                      }
                  });
}
//添加指定数据 fname1%fvalue1$fname2%fvalue2
function hcdoadd(tablename, fnamevalue, callback) {
    hcdoadd2017(tablename, fnamevalue, 0, "", callback);
}
var hcui_ajaxasync = true;
//dataneedtouser是否要自动添加操作人信息
//hcrainset特殊处理说明   删除旧的  {del_old_by:true,delbyfile_name:字段ID} 
//setasync 同步 /异步true/false
//dataneedtouser 是否要自动添加当前操作人信息
//ywcheckonly 唯一性分析
function hcdoadd2017(tablename, fnamevalue, dataneedtouser, hcrainset, callback) {
    hcdoadd201702(tablename, fnamevalue, dataneedtouser, hcrainset, "", callback);
}
//表 字段及值 是否要自动添加操作人信息  特殊处理说明 唯一性分析(ftype,fnv1#当前序号已存在!)
function hcdoadd201702(tablename, fnamevalue, dataneedtouser, hcrainset, ywcheckonly, callback) {
    $.ajax({
        type: "post",
        url: spPageUrl,
        data: {
            "action": "doadd",
            "tablename": tablename,
            "fnamevalue": fnamevalue,
            "dataneedtouser": dataneedtouser,
            "hcrainset": hcrainset,
            "ywcheckonly": ywcheckonly
        },
        timeout: 9000,
        async: hcui_ajaxasync,
        cache: false,
        error: function (error) {
            callback("error");
        },
        success: function (data) {
            var result = JSON.parse(data);
            switch (result.message) {
                case JsonResult.Success:

                    callback("ok");
                    break;
                case JsonResult.Error:
                    callback(result.data);
                    break;
                default:
                    break;
            }

        }
    });
}

//表 字段及值 是否要自动添加操作人信息  特殊处理说明 唯一性分析(ftype,fnv1#当前序号已存在!)，1代表要返回ID
function hcdoadd201703(tablename, fnamevalue, dataneedtouser, hcrainset, ywcheckonly, hcrainbackid, callback) {
    $.ajax({
        type: "post",
        url: spPageUrl,
        data: {
            "action": "doadd",
            "tablename": tablename,
            "fnamevalue": fnamevalue,
            "dataneedtouser": dataneedtouser,
            "hcrainset": hcrainset,
            "ywcheckonly": ywcheckonly,
            "hcrainbackid": hcrainbackid//1代表要返回ID
        },
        timeout: 9000,
        async: hcui_ajaxasync,
        cache: false,
        error: function (error) {
            callback("error");
        },
        success: function (data) {
            var result = JSON.parse(data);
            callback(result);
        }
    });
}

//更新指定数据 fname1%fvalue1$fname2%fvalue2
function hcdoedit(tablename, key, id, fnamevalue, callback) {
    $.ajax({
        type: "post",
        url: spPageUrl,
        data: {
            "action": "doedit",
            "tablename": tablename,
            "tablemidname": key,
            "id": id,
            "fnamevalue": fnamevalue
        },
        timeout: 6000,
        async: hcui_ajaxasync,
        cache: false,
        error: function (error) {
            callback("error");
        },
        success: function (data) {
            var result = JSON.parse(data);
            switch (result.message) {
                case JsonResult.Success:
                    callback(result.data);
                    break;
                case JsonResult.Error:
                    callback(result.data);
                    break;
                default:
                    break;
            }

        }
    });
}
//能用查询 select table where groupby having order callback
function hcdoselbyPost(s, t, w, g, h, o, callback) {

    $.ajax({
        type: "post",
        url: spPageUrl,
        data: {
            "action": "SqlTableByPost",
            "fselect": s,
            "ftable": t,
            "fwhere": w,
            "fgroup": g,
            "forder": o,
            "fhaving": h
        },
        timeout: 6000,
        async: hcui_ajaxasync,
        cache: false,
        error: function (error) {
            callback("error");
        },
        success: function (data) {
            var result = JSON.parse(data);
            switch (result.message) {
                case JsonResult.Success:
                    callback(result.data);
                    break;
                case JsonResult.Error:
                    callback(result.data);
                    break;
                default:
                    break;
            }

        }
    });
}

//能用查询 select table where groupby having order callback
function hcdosels(s, t, w, g, h, o, callback) {
    $.get(sposelUrlByF(s, t, w, g, h, o) + "&timenow=" + new Date().getTime(),
            function (data) {
                callback(data);
            });
}
//能用查询 select table where groupby having order callback
function hcdosel(s, t, w, g, h, o, callback) {
    $.get(sposelUrlByFNoState(s, t, w, g, h, o) + "&timenow=" + new Date().getTime(),
            function (data) {
                callback(data);
            });
}
//通用导出
function toolExport() {
    hcdoExport("T.*", selTableinfo, "", "", "", "");
}
function hcdoExport(s, t, w, g, h, o) {
    var url = spPageUrl + "?action=Export&sqlinfo=" + escape("select[" + s + "]table[" + t + "]where[" + w + "]group[" + g + "]having[" + h + "]order[" + o + "]");
    url = url.replaceAll("'", "hcdhc");
    window.open(url);
}
function toolImport(parm) {
    $('#importForm')[0].reset();
    $("#importMsg").text("");
    $("#action").val("Import");
    $('#ImportShow').window({ title: "导入信息" });
    $('#ImportShow').window('open');
}
function Import(parmf, parmv) {
    if (parmf)
        $("#importForm").attr("action", (" ../ashx/sp.ashx?" + parmf + escape(parmv)));
    if ($("#importFile").val() == "") {
        $("#importMsg").text("请选择上传文件！").addClass("waringMsg");
        return;
    }
    $("#importForm").ajaxSubmit({
        success: function (message) {
            var data = JSON.parse(message);
            if (data.message == JsonResult.Success) {
                $("#importMsg").text(data.data).addClass("successMsg");
            }
            else {
                $("#importMsg").text(data.data).addClass("waringMsg");
            }
        }
    });

}
//生成理伦唯一ID
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function NewGuid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
//调用外部winform窗体    调用的标识（方法）-主状态-信息-回调方法(必须为两个参数 funciotn (p1,p2)  没有时，为空字符串)
function callForm(callfunction, state, message, callback) {
    window.external.callform(callfunction, state, message, callback);
}
//以下可公用
function SetSelectWithObjIdName(sel, stringjson) {
    $(sel).children().remove();
    if (stringjson == "") return;
    var objData = JSON.parse(stringjson);
    $(sel).append("<option value='' selected='selected'></option>");
    for (var i = 0; i < objData.length; i++) {
        if (i == 0) {
            $(sel).append("<option value='" + objData[i].id + "' >" + objData[i].name + "</option>");
        } else {
            $(sel).append("<option value='" + objData[i].id + "'>" + objData[i].name + "</option>");
        }

    }
}
//以下可公用
//生成下拉
function SetSelectWithArrayIdName(sel, objData, nullshowname,nullvalue) {
    $(sel).children().remove();
    thisnullvalue = ""; if (nullvalue) thisnullvalue = nullvalue;
    if (nullshowname) {
        $(sel).append("<option value='" + thisnullvalue + "' selected='selected'>" + nullshowname + "</option>");
    }
    else $(sel).append("<option value='" + thisnullvalue + "' selected='selected'></option>");
    for (var i = 0; i < objData.length; i++) {
        if (i == 0) {
            $(sel).append("<option value='" + objData[i].id + "' >" + objData[i].name + "</option>");
        } else {
            $(sel).append("<option value='" + objData[i].id + "'>" + objData[i].name + "</option>");
        }
    }
}
//生成复选栏(divid:位置的div, infoid:保存信息的id,objData:复选的数据对象)
function SetCheckBoxsInfo(divid, infoid, objData) {
    var testhtml = "<input type='checkbox' id='" + infoid + "' name='" + infoid + "' value='checked' checked='checked' class='hccheckbox' style='display: none;' />" +
          "<div class='formControls  skin-minimal col-7'>";
    for (var i = 0; i < objData.length; i++) {
        testhtml = testhtml + "<div class='check-box'>" +
         "    <input type='checkbox' id='" + infoid + i + "' name='" + infoid + "' value='" + objData[i].id + "' />" +
         "    <label for='" + infoid + i + "'>" + objData[i].name + "</label>" +
        " </div>";
    }

    testhtml = testhtml + " </div>";
    $(divid).html(testhtml);
}
//要传给父页面的内容
var setToParent = [];
/*关闭弹出框口*/
function layer_close() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.setToParent = setToParent;
    parent.layer.close(index);
}
/*弹出通用图片上传框  保存文件ID   显示文件的 ID   */
function addhcrainImg(imgsaveid, imgshowid) {
    layer.open({
        type: 2,
        area: ['350px', '400px'],
        fix: false,
        offset: '0px',//	只定义top坐标，水平保持居中 ffset: ['100px', '50px']	同时定义top、left坐标
        anim: 3,//动画
        moveOut: true,// - 是否允许拖拽到窗口外
        shadeClose: true,// - 是否点击遮罩关闭
        maxmin: false,
        shade: 0.4,
        title: "上传图片",
        content: "hcrain_addimg.html?imgsaveid=" + imgsaveid + "&imgshowid=" + imgshowid,
        end: function () {

        }
    });
}
function addhcrainImgAll(imgsaveid, imgshowid) {
    layer.open({
        type: 2,
        area: ['350px', '400px'],
        fix: false,
        offset: '0px',//	只定义top坐标，水平保持居中 ffset: ['100px', '50px']	同时定义top、left坐标
        anim: 3,//动画
        moveOut: true,// - 是否允许拖拽到窗口外
        shadeClose: true,// - 是否点击遮罩关闭
        maxmin: false,
        shade: 0.4,
        title: "上传图片",
        content: "../hsctask/hcrain_addimg.html?imgsaveid=" + imgsaveid + "&imgshowid=" + imgshowid,
        end: function () {

        }
    });
}
function hcrainopenhtml(url, titlename) {
    var index = layer.open({
        type: 2,
        title: titlename,
        content: url,
        end: function () {

        },
        btn: ['关闭'] //只是为了演示
  , yes: function () {
      layer.closeAll();// $(that).click(); //此处只是为了演示，实际使用可以剔除
  }
    });
    layer.full(index);
}
/*显示图片的控件ID   imgshowId,  文件ID fieldid*/
function hcrainloadimg(imgshowId, fieldid) {
    hcdosel("fsaveurl", "sysfileinfo", "fieldid='" + fieldid + "'", "", "", "id", function (data) {
        var datajson = JSON.parse(data);
        $(imgshowId).attr("src", "../" + datajson[0].fsaveurl);
    });
}
/*tab选项卡*/
jQuery.Huitab = function (tabBar, tabCon, class_name, tabEvent, i) {
    var $tab_menu = $(tabBar);
    // 初始化操作
    $tab_menu.removeClass(class_name);
    $(tabBar).eq(i).addClass(class_name);
    $(tabCon).hide();
    $(tabCon).eq(i).show();

    $tab_menu.on(tabEvent, function () {
        $tab_menu.removeClass(class_name);
        $(this).addClass(class_name);
        var index = $tab_menu.index(this);
        $(tabCon).hide();
        $(tabCon).eq(index).show();
    });
}

/*折叠*/
jQuery.Huifold = function (obj, obj_c, speed, obj_type, Event) {
    if (obj_type == 2) {
        $(obj + ":first").find("b").html("-");
        $(obj_c + ":first").show();
    }
    $(obj).on(Event, function () {
        if ($(this).next().is(":visible")) {
            if (obj_type == 2) {
                return false;
            } else {
                $(this).next().slideUp(speed).end().removeClass("selected");
                if ($(this).find("b")) {
                    $(this).find("b").html("+");
                }
            }
        }
        else {
            if (obj_type == 3) {
                $(this).next().slideDown(speed).end().addClass("selected");
                if ($(this).find("b")) {
                    $(this).find("b").html("-");
                }
            } else {
                $(obj_c).slideUp(speed);
                $(obj).removeClass("selected");
                if ($(this).find("b")) {
                    $(obj).find("b").html("+");
                }
                $(this).next().slideDown(speed).end().addClass("selected");
                if ($(this).find("b")) {
                    $(this).find("b").html("-");
                }
            }
        }
    });
}


/*textarea 字数限制*/
function textarealength(obj, maxlength) {
    var v = $(obj).val();
    var l = v.length;
    if (l > maxlength) {
        v = v.substring(0, maxlength);
    }
    $(obj).parent().find(".textarea-length").text(v.length);
}
//根据ID 获取 Json 对象信息
function hcgetJsonObjById(jsonObj, id) {
    for (var i = 0; i < jsonObj.length; i++) {
        if (jsonObj[i].id == id) { return jsonObj[i]; }
    }
    return [];
}


Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


//能用查询 select table where groupby having order callback
function hcapipost(actionurl, indata, callback) {
    $.ajax({
        type: "post",
        url: actionurl,
        data: JSON.stringify(indata),
        contentType: "application/json", //必须有
        dataType: "json",
        timeout: 6000,
        async: hcui_ajaxasync,
        cache: false,
        error: function (error) {
            console.log(error);
        },
        success: function (data) {
            callback(data);
        }
    });
}

function hcrainchange(u, t, s, w, callback) {
    if (u == "") {
        u = "../api/HcrainTool/PostHcRainChange";
    }
    $.ajax({
        type: "post",
        url: u,
        data: JSON.stringify({ "table": t, "setinfo": s, "whereinfo": w }),
        contentType: "application/json", //必须有
        dataType: "json",
        timeout: 6000,
        async: hcui_ajaxasync,
        cache: false,
        error: function (error) {
            console.log(error);
        },
        success: function (data) {
            callback(data);
        }
    });
}

function hcapiget(actionurl, indata, callback) {
    $.ajax({
        type: "get",
        url: actionurl,
        data: indata,
        dataType: "json",
        timeout: 6000,
        async: hcui_ajaxasync,
        cache: false,
        error: function (error) {
            layer.msg('api' + actionurl + '请求有异常：' + error, { icon: 2 });
            console.log(error);
        },
        success: function (data) {
            callback(data);
        }
    });
}
function hcapigetNoError(actionurl, indata, callback) {
    $.ajax({
        type: "get",
        url: actionurl,
        data: indata,
        dataType: "json",
        timeout: 30000,
        async: true,
        cache: false,
        error: function (error) {

            console.log(error);
        },
        success: function (data) {
            callback(data);
        }
    });
}
//是数值
function hcisnum(invalue) {
    if (invalue == "0") return true;
    if (invalue == null || invalue == "" || invalue == " " || isNaN(invalue)) {
        return false
    }
    else return true;
}
//是数值且不能少于0
function hcisbnum(invalue) {
    if (invalue == null || invalue == "" || invalue == " " || isNaN(invalue) || invalue <= 0) {
        return false
    }
    else return true;
}


//第五种方法  
var idTmr;
function getExplorer() {
    var explorer = window.navigator.userAgent;
    //ie  
    if (explorer.indexOf("MSIE") >= 0) {
        return 'ie';
    }
        //firefox  
    else if (explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
    }
        //Chrome  
    else if (explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
    }
        //Opera  
    else if (explorer.indexOf("Opera") >= 0) {
        return 'Opera';
    }
        //Safari  
    else if (explorer.indexOf("Safari") >= 0) {
        return 'Safari';
    }
}
function hcrainOpenDiv(name, url) {
    var index = layer.open({
        type: 2,
        title: name,
        content: url
    });
    layer.full(index);
}



function method5(tableid) {
    if (getExplorer() == 'ie') {
        var curTbl = document.getElementById(tableid);
        var oXL = new ActiveXObject("Excel.Application");
        var oWB = oXL.Workbooks.Add();
        var xlsheet = oWB.Worksheets(1);
        var sel = document.body.createTextRange();
        sel.moveToElementText(curTbl);
        sel.select();
        sel.execCommand("Copy");
        xlsheet.Paste();
        oXL.Visible = true;

        try {
            var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
        } catch (e) {
            print("Nested catch caught " + e);
        } finally {
            oWB.SaveAs(fname);
            oWB.Close(savechanges = false);
            oXL.Quit();
            oXL = null;
            idTmr = window.setInterval("Cleanup();", 1);
        }

    }
    else {
        tableToExcel(tableid)
    }
}

var tableToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,',
            template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
            base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
            format = function (s, c) {
                return s.replace(/{(\w+)}/g,
                        function (m, p) { return c[p]; })
            }
    return function (table, name) {
        if (!table.nodeType) table = document.getElementById(table)
        var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
        window.location.href = uri + base64(format(template, ctx))
    }
})();